import { useEffect, useState } from 'react';
import styles from './index.module.less';
import SearchForm from './components/serchForm';
import { Button, Form, Modal, Space, Table, message } from 'antd';
import { getUserList, delUser } from '../../services/user';
import AddForm from './components/addForm';

const Index = () => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState([]);
  const [modalVisable, setModalVisable] = useState(false);
  const [loading, setLoading] = useState(false);
    
  const columns = [
    {
      title: '账号',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      render: (_t: any, row: any) => (
        <Space>
          {/* <Button onClick={() => handEdit(row)} type='link'>编辑</Button> */}
          <Button onClick={() => handlerDel(row.id)} type='link'>删除</Button>
        </Space>
      )
    },
  ];

  const queryList = async (page: number) => {
    setLoading(true);
    const data = form.getFieldsValue();
    try {
      const res = await getUserList({ ...data, page });
      if (res.data.code === 200) {
        setDataSource(res.data.data.rows);
        // setTotal(res.data.total);
      }
    } catch (error) {
      
    }
    setLoading(false);
  };

  const handlerSearch = () => {
    queryList(1);
  };

  const handlerDel = (id: number) => {
    Modal.confirm({
      title: '删除用户',
      content: '是否删除该用户',
      okText: '删除',
      cancelText: '取消',
      onOk: async () => {
        try {
          await delUser({id});
        } catch (error: any) {
          message.warning(error.message);
        }
        handlerSearch();
      },
    });
  };

  // const handEdit = (record: any) => {

  // };

  useEffect(() => {
    handlerSearch();
  }, []);

  const handlerCloseModal = () => {
    setModalVisable(false);
    handlerSearch();
  };

  return (
    <div className={styles.container}>
      <SearchForm form={form} onSearch={handlerSearch} />
      <Space>
        <Button onClick={() => setModalVisable(true)} type="primary">添加用户</Button>
      </Space>
      <div className={styles.table}>
        <Table
          key="id"
          loading={loading}
          dataSource={dataSource}
          columns={columns}
        />
      </div>
      {modalVisable && <AddForm onClose={handlerCloseModal} />}
    </div>
  );
};

export default Index;
